package y_2025.m11.d11;

import java.util.concurrent.atomic.AtomicReference;

// 正确方案：使用AtomicReference包装整个状态
public class SafeBankAccount {
    static class AccountState {
        final int balance;
        final int version;
        AccountState(int balance, int version) {
            this.balance = balance;
            this.version = version;
        }
    }
    
    private AtomicReference<AccountState> state =
        new AtomicReference<>(new AccountState(100, 0));
    
    public void transfer(int amount) {
        AccountState oldState;
        AccountState newState;
        do {
            oldState = state.get();
            newState = new AccountState(
                oldState.balance + amount, 
                oldState.version + 1
            );
        } while (!state.compareAndSet(oldState, newState));
    }
}